import router from './router'
import store from './store'
import { getToken } from './utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 进度条配置：不隐藏
NProgress.configure({
    showSpinner: false
})

// 白名单
const whiteList = ['/login']

// 全局前置钩子：未登录无法访问登录以外的网页
router.beforeEach((to, from, next) => {
    // 开启进度条
    NProgress.start()

    // 判断是否登录
    if (getToken()) {
        if (to.path === '/login') {
            next('/')
            NProgress.done()
        } else {
            store.dispatch('GetUserInfo').then(() => {
                next()
            }).catch(err => {
                store.dispatch('Logout').then(() => {
                    next('/login')
                })
            })
        }

    } else {
        if (whiteList.indexOf(to.path) !== -1) next()
        else {
            next('/login')
            NProgress.done()
        }
    }

})

// 路由后置钩子
router.afterEach(() => {
    NProgress.done()
})
